package handler

import (
	"article-info-sys/model"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"strconv"
)

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	filename := uuid.NewString() + ".png"
	path := "static/img/" + filename
	URL := "http://127.0.0.1:8000/" + path
	err := c.SaveUploadedFile(file, "./"+path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件上传失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "文件上传成功",
			"URL":  URL,
		})
		return
	}
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	author := c.PostForm("author")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if title == "" || author == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Article{
		Title:   title,
		Author:  author,
		Content: content,
		Img:     img,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var article []model.Article
	var total int64
	model.DB.Model(&article).Count(&total)
	err := model.DB.Offset(offset).Limit(size).Find(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code":  200,
			"msg":   "查询成功",
			"data":  article,
			"total": total,
		})
		return
	}
}
